<template>
  <view class="upload-exam-container">
    <view class="form-title">上传月考</view>
    
    <view class="form-group">
      <text class="label">标题 <text class="required">*</text></text>
      <input v-model="form.title" type="text" placeholder="请输入月考标题" 
      @input="handleTitleInput" @touchstart.stop/>
    </view>
    
    <view class="form-group">
      <text class="label">Excel文件 <text class="required">*</text></text>
      <view class="upload-area">
        <button @click="selectFile">选择文件</button>
        <text v-if="selectedFileName">{{ selectedFileName }}</text>
        <text v-if="uploadMessage" class="upload-message">{{ uploadMessage }}</text>
      </view>
    </view>
    
    <view class="form-actions">
      <button class="cancel-btn" @click="cancel">取消</button>
      <button class="upload-btn" @click="upload" :disabled="!form.title || !selectedFile">上传</button>
    </view>
  </view>
</template>

<script>
import request from '@/utils/request.js';

export default {
  data() {
    return {
      form: {
        title: '',
        file: null
      },
      selectedFile: null,
      selectedFileName: '',
      uploadMessage: ''
    }
  },
  mounted() {
      // 确保form.title为字符串
      this.form.title = String(this.form.title || '');
    },
  methods: {
    // 选择文件
        selectFile() {
          uni.chooseFile({
            count: 1,
            type: 'file',
            extension: ['.xlsx', '.xls'],
            success: (res) => {
              	this.selectedFile = res.tempFiles[0];
          	this.selectedFileName = res.tempFiles[0].name;
          	this.uploadMessage = '';
            },
            fail: (err) => {
              uni.showToast({
                title: '选择文件失败',
                icon: 'none'
              });
              console.error('选择文件失败', err);
            }
          });
        },

	handleTitleInput(e) {
      this.form.title = e.target.value.trim(); // 实时更新并去除首尾空格
    },


		// 格式化文件大小
		formatFileSize(bytes) {
		  if (bytes === 0) return '0 B';
		  const k = 1024;
		  const sizes = ['B', 'KB', 'MB', 'GB'];
		  const i = Math.floor(Math.log(bytes) / Math.log(k));
		  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
		},
    
    async upload() {
      if (!this.form.title) {
        uni.showToast({
          title: '请输入标题',
          icon: 'none'
        });
        return;
      }
      
      if (!this.selectedFile) {
        uni.showToast({
          title: '请选择Excel文件',
          icon: 'none'
        });
        return;
      }
      
      this.uploadMessage = '上传中...';
      
      try {
        const formData = new FormData();
        formData.append('title', this.form.title);
        formData.append('file', this.selectedFile);
        
        const res = await request.post('/api/score/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        console.log("上传月考成绩结果：" + res)
        // if (res.code === 200) {
		this.uploadMessage = '上传成功';
		uni.showToast({
			title: '月考上传成功',
			icon: 'success'
		});
		
		setTimeout(() => {
			uni.navigateBack();
		}, 1500);
        
      } catch (error) {
        this.uploadMessage = error.message || '网络错误，请稍后重试';
        console.error('上传月考错误:', error);
        uni.showToast({
          title: error.message || '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    },
    
    cancel() {
      uni.navigateBack();
    }
  }
}
</script>

<style>
.upload-exam-container {
  padding: 15px;
}

.form-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: center;
}

.form-group {
  margin-bottom: 15px;
}

.label {
  display: block;
  margin-bottom: 5px;
  font-size: 16px;
}

.required {
  color: #f56c6c;
}

uni-input{
	height: auto;
	min-height: 32px;
	  overflow: visible;
}

uni-input input {
  caret-color: #000; 
  width: 100%;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-sizing: border-box;
  outline: none; /* 添加轮廓，确认输入框可点击 */
  -webkit-user-select: text;
  user-select: text;
}

.upload-area {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.upload-area button {
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  margin-right: 10px;
}

.upload-message {
  color: #f56c6c;
  margin-left: 10px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.cancel-btn {
  padding: 10px 20px;
  background-color: #f5f7fa;
  color: #606266;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-right: 10px;
}

.upload-btn {
  padding: 10px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
}

.upload-btn:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
}
</style>